package cn.lyjuan.dwz_manage.core.java.exception;


import cn.lyjuan.dwz_manage.core.java.util.ActionUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by ly on 2015/1/11.
 */
public class ExceptionResolver extends AbstractHandlerExceptionResolver
{
    private static Logger log = LogManager.getLogger(ExceptionResolver.class.getName());

    @Override
    public ModelAndView doResolveException(HttpServletRequest req, HttpServletResponse resp, Object handler, Exception e)
    {
        logExce(e);// 打印日志

        boolean isAjax = ActionUtils.isAjaxRequest(req);// 是否为 ajax 请求

        return isAjax ? ajaxExce(req, resp, handler, e) : pageExce(req, resp, handler, e);
    }

    /**
     * 后台 ajax 异常，后台会将所有的错误状态码转换为 {@code MgRetCode.ERR}
     * @param req
     * @param resp
     * @param handler
     * @param e
     * @return
     */
    public ModelAndView ajaxExce(HttpServletRequest req, HttpServletResponse resp, Object handler, Exception e)
    {
        String json = null;
        String msg  = null;

        if (e instanceof AccessDeniedException)
        {
            msg = "没有足够的权限";
        }
        else if (e instanceof DwzManageException)
        {
            DwzManageException infoE = (DwzManageException) e;

            msg = infoE.getMessage();
        } else
            msg = "系统繁忙";

        json = ActionUtils.getDWZajaxReturn(ErrorCode.Mg.ERR, msg);

        // 返回 JSON 数据
        ActionUtils.returnAjax(req, resp, json);

        return new ModelAndView();
    }

    /**
     * 后台 page 异常
     * @param req
     * @param resp
     * @param handler
     * @param e
     * @return
     */
    public ModelAndView pageExce(HttpServletRequest req, HttpServletResponse resp, Object handler, Exception e)
    {
        String msg = null;

        if (e instanceof AccessDeniedException)
        {
            msg = "没有足够的权限";
        }
        else if (e instanceof DwzManageException)
        {
            DwzManageException infoE = (DwzManageException) e;

            msg = infoE.getMessage();
        }

        return new ModelAndView("redirect:/dwz/500.jsp", ErrorCode.Mg.MSG_NAME, msg);
    }

    /**
     * 打印错误信息
     * @param e
     */
    private void logExce(Exception e)
    {
        if (e instanceof AccessDeniedException)
        {
            log.warn("权限不足", e);
        }
        else if (e instanceof DwzManageException)
        {
            DwzManageException info = (DwzManageException) e;

            log.error("错误信息 " + info.getMessage());
        } else
        {
            log.error("系统异常", e);
        }
    }
}
